/****************************************************************************
 *
 *   Copyright (c) 2023 PX4 Development Team. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 * 3. Neither the name PX4 nor the names of its contributors may be
 *    used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 ****************************************************************************/

/**
 * @file pwm_direct.cpp
 *
 * Direct PWM control utility - bypass all control allocation
 */

#include <px4_platform_common/log.h>
#include <px4_platform_common/module.h>
#include <px4_platform_common/getopt.h>
#include <drivers/drv_pwm_output.h>
#include <systemlib/err.h>

extern "C" __EXPORT int pwm_direct_main(int argc, char *argv[]);

static void usage(const char *reason);

static void usage(const char *reason)
{
	if (reason) {
		PX4_WARN("%s", reason);
	}

	PRINT_MODULE_DESCRIPTION(
		R"DESCR_STR(
### Description
Direct PWM control - bypass all control allocation layers.
Set PWM values directly on specific channels without going through the normal mixer/control allocator.

WARNING: remove all props before using this command!

### Examples
Set channel 9 (motor 9) to 1500 us:
$ pwm_direct set 9 1500

Set channel 9 to 80% throttle (approx 1700us):
$ pwm_direct set 9 1700

Reset channel 9 to disarmed state (1000us):
$ pwm_direct set 9 1000
)DESCR_STR");

	PRINT_MODULE_USAGE_NAME("pwm_direct", "command");
	PRINT_MODULE_USAGE_COMMAND("set");
	PRINT_MODULE_USAGE_PARAM_INT('c', -1, 1, 16, "PWM channel number (1-16)", false);
	PRINT_MODULE_USAGE_PARAM_INT('v', 1000, 1000, 2000, "PWM value in microseconds (1000-2000)", false);
	PRINT_MODULE_USAGE_DEFAULT_COMMANDS();
}

int pwm_direct_main(int argc, char *argv[])
{
	if (argc < 2) {
		usage("Missing command");
		return 1;
	}

	if (strcmp(argv[1], "set") == 0) {
		int channel = -1;
		int pwm_value = 1000;
		int myoptind = 1;
		const char *myoptarg = nullptr;

		while ((myoptind = px4_getopt(argc, argv, "c:v:", &myoptind, &myoptarg)) != EOF) {
			switch (myoptind) {
			case 'c':
				channel = atoi(myoptarg);
				break;

			case 'v':
				pwm_value = atoi(myoptarg);
				break;

			default:
				usage(nullptr);
				return 1;
			}
		}

		if (channel < 1 || channel > 16) {
			usage("Invalid channel number (must be 1-16)");
			return 1;
		}

		if (pwm_value < 1000 || pwm_value > 2000) {
			usage("Invalid PWM value (must be 1000-2000)");
			return 1;
		}

		int ret = up_pwm_servo_init(0xFFFF); // Initialize all channels
		if (ret < 0) {
			PX4_ERR("up_pwm_servo_init failed (%i)", ret);
			return 1;
		}

		// Convert from 1-based channel to 0-based index
		int channel_index = channel - 1;

		// Set the PWM value directly
		ret = up_pwm_servo_set(channel_index, pwm_value);

		if (ret != 0) {
			PX4_ERR("up_pwm_servo_set failed for channel %i (%i)", channel, ret);
			return 1;
		}

		PX4_INFO("Successfully set PWM channel %i to %i us", channel, pwm_value);

		// Arm the PWM output to ensure it takes effect
		up_pwm_servo_arm(true, (1 << channel_index));

		return 0;

	} else {
		usage("Unknown command");
		return 1;
	}

	return 0;
